package org.gw.ylc.base.data;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QueryFilter {
	private String field;
	private String valueExpr;
	private String operator;
	private String subSelect;
	private List<QueryFilter> combinedFilters;

	public QueryFilter(String field, String valueExpr, String operator) {
		super();
		this.field = field;
		this.valueExpr = valueExpr;
		this.operator = operator;
	}

	public QueryFilter(String field, QueryFilter... filters) {
		super();
		this.field = field;
		this.combinedFilters = Arrays.asList(filters);
	}

	public QueryFilter() {
		super();
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValueExpr() {
		return valueExpr;
	}

	public void setValueExpr(String valueExpr) {
		this.valueExpr = valueExpr;
	}

	public String getOperator() {
		return operator;
	}

	public void setOperator(String operator) {
		this.operator = operator;
	}

	public List<QueryFilter> getCombinedFilters() {
		return combinedFilters;
	}

	public String getSubSelect() {
		return subSelect;
	}

	public void setSubSelect(String subSelect) {
		this.subSelect = subSelect;
	}

	public void setCombinedFilters(List<QueryFilter> combinedFilters) {
		this.combinedFilters = combinedFilters;
	}

	public Condition toCondition() {
		Condition condition = new Condition();
		condition.setField(field);
		condition.setLogical("and");
		condition.setOperator(operator);
		if (StringUtils.hasText(valueExpr))
			condition.setValue(new Object[] { PermissionContext.eval(valueExpr) });
		if (combinedFilters != null && combinedFilters.size() > 0) {
			List<Condition> subConditions = new ArrayList<Condition>();
			for (QueryFilter sub : combinedFilters) {
				subConditions.add(sub.toCondition());
			}
			condition.setSubConditions(subConditions);
		}
		return condition;
	}
}
